<template>
  <departmentBase>
    <template v-slot:main-left>
      <SearchTrees
        :treeData="treeData"
        :defaultProps="defaultProps"
        :lazy="lazy"
        @deleteHandle="deleteHandle"
        @getlazyLoad="lazyLoad"
        @handleNodeClickTree="handleNodeClickTree"
      />
    </template>
    <!-- 右侧部分 -->
    <template v-slot:search-info>
      <searchMain
        size="mini"
        ref="searchMain"
        :model="formData"
        :itemList="formItemList"
        :searchBtn="searchBtn"
      />
    </template>
    <template v-slot:table-main>
      <div class="depForm" ref="depForm">
        <el-form
          :model="depForm"
          ref="depRuleForm"
          label-width="auto"
          class="demo-ruleForm"
          :rules="rules"
        >
          <div class="top">
            <el-form-item label="上级字典类别" prop="parentName">
              <el-popover
                ref="hisDicTypeListPopover"
                placement="bottom-start"
                trigger="manual"
                v-model="treePopoverVisible"
              >
                <el-tree
                  :data="hisDicTypeList"
                  :props="hisDicTypeListTreeProps"
                  node-key="hisDicTypeId"
                  ref="hisDicTypeListTree"
                  @current-change="hisDicTypeListTreeCurrentChangeHandle"
                  :default-expand-all="false"
                  :highlight-current="true"
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-popover>
              <el-input
                v-model="depForm.parentName"
                v-popover:hisDicTypeListPopover
                :readonly="true"
                :disabled="
                  !disabledItem && formStatus === 'create' ? false : true
                "
                placeholder="点击选择上级字典类别"
                @focus="treePopoverVisible = !treePopoverVisible"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              v-for="item in ItemList"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            >
              <el-input
                v-if="item.type === 'Input'"
                :disabled="disabledItem"
                v-model.trim="depForm[item.prop]"
                :placeholder="item.placeholder"
              />
              <el-input
                v-if="item.type === 'InputNum'"
                :disabled="disabledItem"
                :maxlength="item.maxlength"
                :show-word-limit="item.showWord"
                v-model.number="depForm[item.prop]"
                :placeholder="item.placeholder"
              />
              <el-select
                v-if="item.type === 'Select'"
                :disabled="disabledItem"
                v-model="depForm[item.prop]"
                :style="{ width: '100%' }"
                :placeholder="item.placeholder"
              >
                <el-option
                  v-for="op in item.options"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </el-select>

              <el-switch
                v-if="item.type === 'Delivery'"
                :disabled="disabledItem"
                :active-value="1"
                :inactive-value="0"
                v-model="depForm[item.prop]"
              ></el-switch>
            </el-form-item>
          </div>
          <div class="bottom">
            <el-form-item>
              <el-button
                :disabled="disabledItem"
                type="primary"
                @click="formStatus === 'create' ? create() : update()"
                >确定</el-button
              >
              <el-button :disabled="disabledItem" @click="cancel"
                >取消</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>
  </departmentBase>
</template>
<script>
import departmentBase from "@/components/Layout/departmentBase.vue"
import SearchTrees from "@/components/Trees/SearchTrees.vue"
import searchMain from "@/components/CommonForm/form-item/DepartmentForm.vue"
import { addressList, dataProps } from "@/simdata/healthData.js"
import {
  fetchList,
  GetLazyNodeDicType,
  getObj,
  addObj,
  delObj,
  putObj,
  fetchDicTypeTree
} from "@/api/setup/setup.js"
import success from "@/utils/operation-message.js"
const defaultDictType = {
  parentName: "",
  code: "",
  name: "",
  grade: undefined,
  status: 1,
  remarks: ""
}

export default {
  components: {
    departmentBase,
    SearchTrees,
    searchMain
  },
  data() {
    return {
      // 配置表单按钮
      searchBtn: [
        {
          label: "搜索",
          icon: "el-icon-search",
          type: "primary",
          disabled: false,
          handle: () => this.searchHandle()
        },
        {
          label: "新增",
          icon: "el-icon-circle-plus-outline",
          type: "primary",
          disabled: false,
          handle: () => this.addHandle()
        }
      ],
      formData: {
        keywords: ""
      },
      // 配置树的展示配置
      defaultProps: {
        id: "hisDicTypeId",
        label: "name",
        children: "hisDicTypeVOS",
        isLeaf: "isLeaf"
      },
      // 树的数据
      treeData: [],
      // 配置是否默认加载假数据
      lazy: true,
      formItemList: [
        {
          type: "Input",
          label: "",
          prop: "keywords",
          span: 6,
          placeholder: "科室名称"
        }
      ],
      // 控制下拉框
      treePopoverVisible: false,
      // 配置input框里面的树
      hisDicTypeList: [
        {
          hisDicTypeId: "-1",
          name: "顶级菜单",
          children: []
        }
      ],
      hisDicTypeListTreeProps: {
        id: "hisDicTypeId",
        label: "name",
        children: "children"
      },
      // 提交表单的字段
      depForm: Object.assign({}, defaultDictType),
      // {
      //   upper_dictionary: "", // 上级字典
      //   levelType: "", // 类别编码
      //   name: "", // 类别名称
      //   level: "", // 级别编码
      //   isUser: true, // 是否启用
      //   describe: "" // 描述
      // },
      // 验证字段
      rules: {
        parentName: [
          { required: true, message: "请输入上级字典类别", trigger: "change" }
        ],
        code: [{ required: true, message: "请输入类别编码", trigger: "blur" }],
        name: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        grade: [
          { required: true, message: "级别必须为数字值", trigger: "blur" }
        ]
      },
      // 是新增还是修改
      formStatus: "",
      // 控制禁用
      disabledItem: true,
      oldDictTypeCode: "",
      // 配置显示的提交表单
      ItemList: [
        {
          type: "Input",
          label: "类别编码",
          prop: "code",
          placeholder: "请输入类别编码"
        },
        {
          type: "Input",
          label: "类别名称",
          prop: "name",
          placeholder: "请输入类别名称"
        },
        {
          type: "InputNum",
          label: "级别编码",
          prop: "grade",
          maxlength: "1",
          showWord: true,
          placeholder: "请输入级别编码"
        },
        {
          type: "Delivery",
          label: "是否启用",
          prop: "status",
          placeholder: ""
        },
        {
          type: "Input",
          label: "描述",
          prop: "remarks",
          placeholder: "请输入描述"
        }
      ],
      // top标签的高度
      topHeight: null,
      // 分页查询
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      }
    }
  },
  created() {},
  methods: {
    // 点击搜索树节点
    searchHandle() {
      this.page.currentPage = 1
      this.fetchList()
    },
    // 点击新增按钮
    addHandle() {
      this.disabledItem = false
      this.formStatus = "create"
      this.depForm = Object.assign({}, defaultDictType)
      this.resetForm()
      // console.log(this.depForm)
    },
    resetForm() {
      //重置
      this.$nextTick(() => {
        if (this.$refs["depRuleForm"] !== undefined) {
          this.$nextTick(() => {
            this.$refs["depRuleForm"].resetFields()
          })
        }
        this.$refs["depRuleForm"].clearValidate()
      })
      this.depForm = Object.assign({}, defaultDictType)
    },
    //切换机构
    handleChange() {
      console.log("切换机构")
    },
    // 取消按钮
    cancel() {
      this.disabledItem = true
      this.formStatus = ""
      this.resetForm()
    },
    // 字典树选中
    hisDicTypeListTreeCurrentChangeHandle(data, node) {
      this.depForm.parentId = data.hisDicTypeId
      this.depForm.parentName = data.name
      this.$refs.depRuleForm.validateField("parentName")
      this.treePopoverVisible = false
    },
    // 点击修改
    update() {
      if (this.depForm.systemFlag == 1) {
        this.$message({
          title: "错误",
          message: "系统参数不允许修改",
          type: "error",
          duration: 2000
        })
        return
      }
      this.disabledItem = true
      this.$refs.depRuleForm.validate(async valid => {
        if (!valid) {
          this.disabledItem = false
          return false
        } else {
          const res = await putObj(this.depForm)
          if (res.code === "1000") {
            this.disabledItem = false
            this.cancel()
            this.fetchList()
            success()
          }
        }
      })
    },
    // 点击新增按钮确定
    create() {
      this.disabledItem = true
      this.$refs.depRuleForm.validate(async valid => {
        if (!valid) {
          this.disabledItem = false
          return false
        } else {
          const res = await addObj(this.depForm)
          console.log(res)
          if (res.code === "1000") {
            this.disabledItem = false
            this.cancel()
            this.fetchList()
            success()
          }
        }
      })
    },
    // 点击删除树按钮
    deleteHandle(node, data) {
      if (!node.isLeaf) {
        this.$message({
          title: "错误",
          message: "请先删除下级数据！",
          type: "error",
          duration: 2000
        })
        return
      }
      if (node.systemFlag == 1) {
        this.$message({
          title: "错误",
          message: "系统参数不允许删除",
          type: "error",
          duration: 2000
        })
        return
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const res = await delObj(data.hisDicTypeId)
        if (res) {
          this.cancel()
          this.fetchList()
          success()
        }
      })
    },
    // 获取节点数据
    async handleNodeClickTree(data) {
      this.formStatus = "update"
      this.disabledItem = false
      this.oldDictTypeCode = data.code
      this.treePopoverVisible = false
      this.$refs["depRuleForm"].clearValidate()
      const res = await fetchDicTypeTree(
        Object.assign({
          hisDicTypeId:
            data.parentId === "-1" ? data.hisDicTypeId : data.parentId
        })
      )
      if (res.code === "1000") {
        this.hisDicTypeList[0].children = res.data
      }
      const result = await getObj(data.hisDicTypeId)
      // console.log(result)
      if (result.code === "1000") {
        this.depForm = result.data
      }
      this.$nextTick(() => {
        this.hisDicTypeListTreeSetCurrentNode()
      })
    },

    // 字典树设置当前选中节点
    hisDicTypeListTreeSetCurrentNode() {
      this.$refs.hisDicTypeListTree.setCurrentKey(this.depForm.parentId)
      this.depForm.parentName = (this.$refs.hisDicTypeListTree.getCurrentNode() ||
        {})["name"]
    },
    // 分页查询字典类别
    async fetchList() {
      const res = await fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize
          },
          this.formData
        )
      )
      console.log(res)
      this.treeData = res.data.records
      this.page.total = res.data.total
    },
    // 加载数据
    async lazyLoad(node, resolve) {
      console.log(node)
      if (node.level === 0) {
        const result = this.fetchList()
        console.log(result)
        if (result.code === "1000") {
          return resolve(result.data)
        }
      }
      if (node.level > 0) {
        const res = await GetLazyNodeDicType(node.data.hisDicTypeId)
        console.log(res)
        if (res.code === "1000") {
          return resolve(res.data)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .table-item {
  height: 100%;
  margin-right: 0 !important;
}
.depForm {
  height: 100%;
  .el-form {
    width: 80%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    .top {
      flex: 1;
      padding: 20px 0;
      overflow: hidden;
      overflow-y: auto;
      padding-right: 30px;
    }
    .bottom {
      .el-form-item {
        height: 80px;
        /deep/ .el-form-item__content {
          padding-top: 30px;
        }
      }
    }
  }
}
</style>
